import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoCilent {
    private DatagramSocket socket=null;
    private  String serverIP=" ";
    private  int serverPort=0;
    public UdpEchoCilent(String IP,int port) throws SocketException {
        socket=new DatagramSocket();
        serverIP=IP;
        serverPort=port;
    }
    public  void strat() throws IOException{
        System.out.println("客户端启动！");
        Scanner scanner=new Scanner(System.in);
        while (true){
            System.out.println("->");
            String request=scanner.next();
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoCilent cilent=new UdpEchoCilent("127.0.0.1",9090);
        cilent.strat();
    }

}
